<template>
  <!-- 添加或修改商户推送任务对话框 -->
  <el-drawer size="75%" :title="title" :visible.sync="open">
    <div class="demo-drawer-form">
      <div class="demo-drawer-form__content">
        <div class="" :class="{flex: !isMobile}">
          <div class="" style="width: 540px; max-width: 100%;">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
              <el-form-item label="推送价格:">
                <!-- <el-input
                  readonly
                  v-model="form.priceAmount"
                  placeholder="请输入推送价格"
                /> -->
                <span style="color: red">注意：推送价格=成本价格+提成价格</span>
              </el-form-item>
              <el-form-item label="成本价格" prop="costAmount">
                <el-input-number :min="0" v-model="form.costAmount" placeholder="请输入成本价格" />
                <br>
                <span style="color: red">注意：数据的推给机构的成本价格，如果是代理，填写一条数据的平台收费价格</span>
              </el-form-item>
              <el-form-item label="提成价格" prop="payAmount">
                <el-input-number :min="0" v-model="form.payAmount" placeholder="请输入提成价格" />
                <br>
                <span style="color: red">注意：给代理的提成价格。不是代理商户填0即可</span>
              </el-form-item>

              <el-form-item label="每日推送数量" prop="priceAmount">
                <el-input-number :min="0" v-model="form.pushNumber" placeholder="请输入每日推送数量" />
              </el-form-item>

              <el-form-item label="每日推送时间" prop="formTimes">
                <template v-if="isMobile">
                  <el-time-picker
                    v-model="form.formTimes[0]"
                    value-format="HH:mm:ss"
                    placeholder="开始时间"
                  >
                  </el-time-picker>
                  <div>至</div>
                  <el-time-picker
                    v-model="form.formTimes[1]"
                    value-format="HH:mm:ss"
                    placeholder="结束时间"
                  ></el-time-picker>
                </template>
                <el-time-picker v-else is-range value-format="HH:mm:ss" v-model="form.formTimes" range-separator="至"
                  start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择每日推送时间">
                </el-time-picker>

              </el-form-item>
              <el-form-item label="年龄" prop="formTimes">
                <div :class="{flex: !isMobile}">
                  <el-input-number :min="0" v-model="form.minAge" placeholder="请输入最小年龄" />
                  <div style="margin: 0 8px">至</div>
                  <el-input-number :min="0" v-model="form.maxAge" placeholder="请输入最大年龄" />
                </div>
              </el-form-item>
              <el-form-item label="允许推送流量类型" prop="inChannelType" class="single-line-label">
                <el-select v-model="form.inChannelType" clearable placeholder="请选择渠道名称" filterable multiple>
                  <el-option v-for="(item, i) in extData.flowRateTypeList || []" :key="i" :label="item.key"
                    :value="item.value"></el-option>
                </el-select>
                <br>
                <span style="color: red">注意：选择指定的推送流量类型（可多选），没有限制则不选择</span>
              </el-form-item>
              <el-form-item label="允许推送渠道" prop="inChannelArray" class="single-line-label">
                <el-select v-model="form.inChannelArray" clearable placeholder="请选择渠道名称" filterable multiple>
                  <el-option v-for="(item, i) in extData.channelNameOpen || []" :key="i" :label="item.key"
                    :value="item.value"></el-option>
                </el-select>
                <br>
                <span style="color: red">注意：选择指定的推送渠道（可多选），没有限制则不选择</span>
              </el-form-item> <el-form-item label="不允许渠道" prop="outChannelArray" class="single-line-label">
                <el-select v-model="form.outChannelArray" clearable placeholder="请选择渠道名称" filterable multiple>
                  <el-option v-for="(item, i) in extData.channelNameOpen || []" :key="i" :label="item.key"
                    :value="item.value"></el-option>
                </el-select>
                <br>
                <span style="color: red">注意：选择不允许推送渠道（可多选），没有限制则不选择</span>
              </el-form-item>





              <el-form-item label="不推送" prop="notPushDayWeek">
                <el-checkbox-group v-model="form.notPushDayWeek">
                  <el-checkbox label="周一" value="1"></el-checkbox>
                  <el-checkbox label="周二" value="2"></el-checkbox>
                  <el-checkbox label="周三" value="3"></el-checkbox>
                  <el-checkbox label="周四" value="4"></el-checkbox>
                  <el-checkbox label="周五" value="5"></el-checkbox>
                  <el-checkbox label="周六" value="6"></el-checkbox>
                  <el-checkbox label="周日" value="7"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>

              <!-- <el-form-item label="任选" prop="orFilter">
                <el-checkbox-group v-model="form.orFilter">
                  <el-checkbox
                    v-for="orFilterItem in item.children"
                    :key="orFilterItem.value"
                    :label="orFilterItem.name"
                    :value="orFilterItem.value"></el-checkbox>
                </el-checkbox-group>
              </el-form-item> -->

              <el-form-item v-for="item in dynamicParamList" :key="item.filedName" :label="item.name"
                :prop="item.filedName">
                <el-select style="width: 100%" v-model="form[item.filedName]" multiple :placeholder="`请选择${item.name}`">
                  <el-option v-for="itemOp in item.children" :key="itemOp.value" :label="itemOp.name"
                    :value="itemOp.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <el-form ref="form1" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="推送的省市" prop="cityInfo">
              <el-tree :data="addressInfoList" show-checkbox auto-expand-parent node-key="cityCode" ref="cityInfoTree"
                :props="{
                  children: 'children',
                  label: 'city',
                }">
              </el-tree>
            </el-form-item>
          </el-form>
          <el-form ref="form2" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="不推送的省市" prop="outCityArray">
              <el-tree :data="addressInfoList" show-checkbox auto-expand-parent node-key="cityCode"
                ref="outCityArrayTree" :props="{
                  children: 'children',
                  label: 'city',
                }">
              </el-tree>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="demo-drawer-form__footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button v-if="!isNoUpdate" type="primary" @click="submitForm" :loading="loading">{{
          loading ? "提交中 ..." : "确 定"
          }}</el-button>
      </div>
    </div>
    <TanChuang ref="TanChuangRef" />
  </el-drawer>
</template>

<script>
import { listAddressInfo } from "@/api/addressInfo/addressInfo";
import { baseInfoExtData, } from "@/api/channel/baseInfo";
import { listTaskDictInfo } from "@/api/dict/dictInfo";
import {
addTaskInfo,
updateTaskInfo
} from "@/api/merchant/taskInfo";
import { isMobile } from 'mobile-device-detect';
import TanChuang from './TanChuang.vue'
const notPushDayWeekMap = {
  周一: "1",
  周二: "2",
  周三: "3",
  周四: "4",
  周五: "5",
  周六: "6",
  周日: "7",
};
export default {
  name: "AddEditDrawer",
  components: {
    TanChuang
  },
  props: {
    infoId: {
      type: String | Number,
      required: true,
    },
  },
  data() {
    return {
      isMobile,
      // 遮罩层
      loading: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      extData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        infoId: null,
      },
      dynamicParamList: [], // 动态参数信息
      addressInfoList: [], //地址树结构信息
      // 表单参数
      form: {},
      row: {},
      // 表单校验
      rules: {},
      isNoUpdate: false,
    };
  },
  created() {
    this.reset();
    this.getTreeselect();
    this.getListAddressInfo();
    this.getOptions();
  },

  methods: {
    getOptions() {
      baseInfoExtData().then((response) => {
        this.extData = response.data;
      });
    },
    show(row, isNoUpdate) {
      if (!row) this.reset();
      this.isNoUpdate = isNoUpdate;
      this.open = true;
      if (row) {
        this.title = isNoUpdate ? '查看商户推送任务' : "修改商户推送任务";
      } else {
        this.title = "添加商户推送任务";
      }
      this.$nextTick(() => {
        this.reset(row);
      });
    },
    /** 查询地址列表列表 */
    getListAddressInfo() {
      listAddressInfo().then((response) => {
        this.addressInfoList = this.handleTree(response.rows, "cityCode");
      });
    },


    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listTaskDictInfo().then((response) => {
        this.dynamicParamList = this.handleTree(response.rows, "id");
        this.convertFieldNamesToCamelCase();
      });
    },

    convertFieldNamesToCamelCase() {
      this.dynamicParamList.forEach((item) => {
        item.filedName = this.snakeCaseToCamelCase(item.filedName);
      });
    },

    snakeCaseToCamelCase(snakeCase) {
      return snakeCase.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset(row) {
      if (row) {
        const postForm = Object.fromEntries(
          Object.entries(row).map(([key, value]) => [
            key,
            (() => {
              if (
                typeof value === "string" &&
                value.startsWith("[") &&
                value.endsWith("]")
              ) {
                try {
                  const tempVal = JSON.parse(value);
                  if (Array.isArray(tempVal)) return tempVal;
                } catch (error) {
                  return value;
                }
                return value;
              }
              return value;
            })(),
          ])
        );
        if (this.$refs.cityInfoTree) {
          this.$refs.cityInfoTree.setCheckedKeys(postForm.cityInfo || []);
          this.$refs.outCityArrayTree.setCheckedKeys(
            postForm.outCityArray || []
          );
        }
        postForm.formTimes = [postForm.starttime, postForm.endtime];
        try {
          const notPushDayWeekReverseMap = Object.fromEntries(
            Object.entries(notPushDayWeekMap).map(([key, value]) => [value, key])
          );
          postForm.notPushDayWeek = typeof postForm.notPushDayWeek === 'string' ? postForm.notPushDayWeek === '' ? [] : [postForm.notPushDayWeek] : postForm.notPushDayWeek
          postForm.notPushDayWeek = postForm.notPushDayWeek.map(
            (item) => notPushDayWeekReverseMap[item]
          );
        } catch (error) {
          postForm.notPushDayWeek = []
        }
        this.form = postForm;
      } else {
        this.form = {
          priceAmount: null,
          costAmount: null,
          payAmount: null,
          // 开始结束时间表单
          formTimes: ['09:00:00', '18:00:00'], // []
          notPushDayWeek: [],
          minAge: 20,
          maxAge: 60,
        };
        this.resetForm("form");
        if (this.$refs.cityInfoTree) {
          this.$refs.cityInfoTree.setCheckedKeys([]);
          this.$refs.outCityArrayTree.setCheckedKeys([]);
        }
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商户推送任务";
    },
    /** 提交按钮 */
    async submitForm() {
      if (!this.infoId) {
        this.$modal.msgError("没有机构id");
        return;
      }
      const tempForm = {
        infoId: +this.infoId,
        ...this.form,
        notPushDayWeek: this.form.notPushDayWeek.map(
          (item) => notPushDayWeekMap[item]
        ),
        starttime: this.form.formTimes?.[0],
        endtime: this.form.formTimes?.[1],
      };
      delete tempForm.formTimes;
      tempForm.cityInfo = this.$refs.cityInfoTree.getCheckedKeys();
      tempForm.outCityArray = this.$refs.outCityArrayTree.getCheckedKeys();
      const postForm = Object.fromEntries(
        Object.entries(tempForm).map(([key, value]) => [
          key,
          Array.isArray(value) ? (value.length > 0 ? JSON.stringify(value) : null) : value,
        ])
      );
      // if (postForm.costAmount <= 0) {
      //   this.$modal.msgError("请输入成本价格");
      //   return;
      // }

      // if (postForm.payAmount < 0) {
      //   this.$modal.msgError("请输入合理的价格");
      //   return;
      // }

      if (!postForm.starttime || !postForm.endtime) {
        this.$modal.msgError("请输入每日推送时间");
        return;
      }

      if (!postForm.cityInfo) {
        this.$modal.msgError("请选择推送的省市");
        return;
      }

      const numberKeys = ['payAmount', 'costAmount']

      this.loading = true;
      const postFormProxy = Object.fromEntries(Object.entries(postForm).map(([key, value]) => [key, numberKeys.includes(key) ? (value || 0) : (value || '')]))

      try {
        await this.$refs.TanChuangRef.show({...postFormProxy}, this.dynamicParamList, this.addressInfoList)
        if (postFormProxy.id) {
          await updateTaskInfo(postFormProxy)
            .then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit("refresh");
            })
        } else {
          await addTaskInfo(postFormProxy)
            .then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$emit("refresh");
            })
        }
      } catch (error) {
        console.error(error)
      }
      this.loading = false
    },
  },
};
</script>
